package com.eims.main.livescores.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.MySingleton;
import com.android.volley.toolbox.StringXmlRequest;
import com.contans.view.BifenGetFootBallTeamVo;
import com.contans.view.MainFenxiRowVo;
import com.contans.view.MainFenxiVo;
import com.contans.view.getINdexFootballdayVo;
import com.eims.sls_app.ui.MainFenixActivity;
import com.eims.sls_app.ui.MainLiveixActivity;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.ImageManager;
import com.eims.sls_app.utils.LotteryUtils;
import com.eims.sls_app.view.MyToast;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import bls.juejin.cn.R;
import progressBar.ProgressDialogBar;

//为ExpandableListView自定义适配器
public class MyExpandableListView extends BaseExpandableListAdapter {
	private Context context;
	private List<getINdexFootballdayVo> maplist;
	private ArrayList<BifenGetFootBallTeamVo> arrayList;

	// Model：定义的数据
	// private String[] groups = { "A", "B", "C" };
	// // 注意，字符数组不要写成{{"A1,A2,A3,A4"}, {"B1,B2,B3,B4，B5"}, {"C1,C2,C3,C4"}}*/
	// private String[][] childs = { { "A1", "A2", "A3", "A4" }, { "A1", "A2", "A3",
	// "B4" }, { "A1", "A2", "A3", "C4" } };
	public MyExpandableListView(Context context, List<getINdexFootballdayVo> maplist) {
		super();
		this.maplist = maplist;
		this.context = context;

	}

	public List<getINdexFootballdayVo> getMaplist() {
		return maplist;
	}

	public void setMaplist(List<getINdexFootballdayVo> maplist) {
		this.maplist = maplist;
	}
public void fresh() {
	notifyDataSetChanged();
}
	// 返回一级列表的个数
	@Override
	public int getGroupCount() {
		if (maplist != null) {
			return maplist.size();
		}
		return 0;
	}

	// 返回每个二级列表的个数
	@Override
	public int getChildrenCount(int groupPosition) { // 参数groupPosition表示第几个一级列表
		Log.d("smyhvae", "-->" + groupPosition);
		if (maplist.get(groupPosition).getBallarrayList() != null) {
			return maplist.get(groupPosition).getBallarrayList().size();
		}
		return 0;
	}

	// 返回一级列表的单个item（返回的是对象）
	@Override
	public Object getGroup(int groupPosition) {
		return maplist.get(groupPosition);
	}

	// 返回二级列表中的单个item（返回的是对象）
	@Override
	public Object getChild(int groupPosition, int childPosition) {
		return maplist.get(groupPosition).getBallarrayList().get(childPosition); // 不要误写成groups[groupPosition][childPosition]
	}

	@Override
	public long getGroupId(int groupPosition) {
		return groupPosition;
	}

	@Override
	public long getChildId(int groupPosition, int childPosition) {
		return childPosition;
	}

	// 每个item的id是否是固定？一般为true
	@Override
	public boolean hasStableIds() {
		return true;
	}

	// 【重要】填充一级列表
	@Override
	public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = LayoutInflater.from(context).inflate(R.layout.caidan_one, null);
			holder.tv_tile = (TextView) convertView.findViewById(R.id.tv_tile);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		if (maplist.get(groupPosition).getTime().equals("over")) {
			holder.tv_tile.setText("完场");
		} else {
			holder.tv_tile.setText(maplist.get(groupPosition).getTime());
		}

		return convertView;
	}

	class ViewHolder {

		TextView tv_tile;

	}

	// 【重要】填充二级列表
	@Override
	public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
			ViewGroup parent) {

		final BifenGetFootBallTeamVo ballTeamVo = maplist.get(groupPosition).getBallarrayList().get(childPosition);

		childViewHolder holder;
		// 判断View是否为空

		if (convertView == null) {
			holder = new childViewHolder();
			convertView = LayoutInflater.from(context).inflate(R.layout.fragment_zq_bifen_item, null);
			holder.tv_team_changci = (TextView) convertView.findViewById(R.id.tv_team_changci);
			holder.tv_team_type = (TextView) convertView.findViewById(R.id.tv_team_type);
			holder.tv_start_time = (TextView) convertView.findViewById(R.id.tv_start_time);
			holder.tv_time_statu = (TextView) convertView.findViewById(R.id.tv_time_statu);
			holder.tv_team_result = (TextView) convertView.findViewById(R.id.tv_team_result);

			// holder.tv_peilv_main = (TextView)
			// convertView.findViewById(R.id.tv_peilv_main);
			// holder.tv_peilv_flat = (TextView)
			// convertView.findViewById(R.id.tv_peilv_flat);
			// holder.tv_peilv_gues = (TextView)
			// convertView.findViewById(R.id.tv_peilv_gues);
			// holder.tv_r_peilv_main = (TextView)
			// convertView.findViewById(R.id.tv_r_peilv_main);
			// holder.tv_r_peilv_slat = (TextView)
			// convertView.findViewById(R.id.tv_r_peilv_slat);
			// holder.tv_r_peilv_gues = (TextView)
			// convertView.findViewById(R.id.tv_r_peilv_gues);

			holder.tv_main_team_num = (TextView) convertView.findViewById(R.id.tv_main_team_num);
			holder.tv_main_team_name = (TextView) convertView.findViewById(R.id.tv_main_team_name);
			holder.tv_main_gues_name = (TextView) convertView.findViewById(R.id.tv_main_gues_name);
			holder.tv_main_gues_num = (TextView) convertView.findViewById(R.id.tv_main_gues_num);

			// holder.lr_peilv_show = (LinearLayout)
			// convertView.findViewById(R.id.lr_peilv_show);

			holder.iv_main_team = (ImageView) convertView.findViewById(R.id.iv_main_team);
			holder.iv_gues_team = (ImageView) convertView.findViewById(R.id.iv_gues_team);

			holder.tv_main_hong = (TextView) convertView.findViewById(R.id.tv_main_hong);
			holder.tv_gues_hong= (TextView) convertView.findViewById(R.id.tv_gues_hong);
			
			
			holder.lr_main_hong = (RelativeLayout) convertView.findViewById(R.id.lr_main_hong);
			holder.lr_gues_hong= (RelativeLayout) convertView.findViewById(R.id.lr_gues_hong);
			
			holder.lr_Whole=(LinearLayout) convertView.findViewById(R.id.lr_whole);
			
			convertView.setTag(holder);
		} else {
			holder = (childViewHolder) convertView.getTag();
		}
		holder.tv_team_changci.setText(getTeamChangci(ballTeamVo.getXid()));
		holder.tv_team_type.setText(ballTeamVo.getLname());

		ImageManager.getInstance().displayImage(ballTeamVo.getHlogo(), holder.iv_main_team,
				ImageManager.getViewsHeadOptions());
		ImageManager.getInstance().displayImage(ballTeamVo.getAlogo(), holder.iv_gues_team,
				ImageManager.getViewsHeadOptions());

		if (ballTeamVo.getHrank() != null && !ballTeamVo.getHrank().equals("")) {
			holder.tv_main_team_num.setText("[" + ballTeamVo.getHrank() + "]");
		} else {
			holder.tv_main_team_num.setText("");
		}
		if (ballTeamVo.getArank() != null && !ballTeamVo.getArank().equals("")) {
			holder.tv_main_gues_num.setText("[" + ballTeamVo.getArank() + "]");
		} else {
			holder.tv_main_gues_num.setText("");
		}
		holder.tv_main_team_name.setText(ballTeamVo.getHteam());
		holder.tv_main_gues_name.setText(ballTeamVo.getAteam());

		if (ballTeamVo.getState().equals("4")) {
			holder.tv_time_statu.setText("完场");
			holder.tv_time_statu.setTextColor(context.getResources().getColor(R.color.black));
			holder.tv_start_time.setVisibility(View.INVISIBLE);

			holder.tv_team_result.setText(ballTeamVo.getHscore() + "  -  " + ballTeamVo.getAscore());
			holder.tv_team_result.setTextColor(context.getResources().getColor(R.color.main_red));
		} else if (ballTeamVo.getState().equals("1")) {
			holder.tv_time_statu.setText("上半场");
			holder.tv_time_statu.setTextColor(context.getResources().getColor(R.color.main_red));
			holder.tv_start_time.setVisibility(View.VISIBLE);
			int getNachTime = 0;
			if (ballTeamVo.getRealtime() != null && !ballTeamVo.getRealtime().equals("")) {
				try {
					getNachTime = LotteryUtils.getBetweenOfDate(ballTeamVo.getRealtime());
					if (getNachTime <= 0) {
						holder.tv_start_time.setText("上半场 0" + "'");
					} else if (getNachTime > 45) {
						holder.tv_start_time.setText("上半场45+" + "'");
					} else {
						holder.tv_start_time.setText("上半场" + getNachTime + "'");
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					holder.tv_start_time.setText("上半场 0'");
					e.printStackTrace();
				}

			} else {
				holder.tv_start_time.setText("上半场 0'");
			}

			holder.tv_team_result.setText(ballTeamVo.getHscore() + "  -  " + ballTeamVo.getAscore());
			holder.tv_team_result.setTextColor(context.getResources().getColor(R.color.main_red));
		} else if (ballTeamVo.getState().equals("2")) {
			holder.tv_time_statu.setText("中场");
			holder.tv_time_statu.setTextColor(context.getResources().getColor(R.color.main_red));
			holder.tv_start_time.setVisibility(View.VISIBLE);
			holder.tv_start_time.setText("比赛中场45'");
			holder.tv_team_result.setText(ballTeamVo.getHscore() + "  -  " + ballTeamVo.getAscore());
			holder.tv_team_result.setTextColor(context.getResources().getColor(R.color.main_red));
		} else if (ballTeamVo.getState().equals("3")) {
			holder.tv_time_statu.setText("下半场");

			int getNachTime = 0;
			if (ballTeamVo.getRealtime() != null && !ballTeamVo.getRealtime().equals("")) {
				try {
					getNachTime = LotteryUtils.getBetweenOfDate(ballTeamVo.getRealtime());
					if (getNachTime <= 0) {
						holder.tv_start_time.setText("下半场 45" + "'");
					} else if (getNachTime > 45) {
						holder.tv_start_time.setText("下半场90+" + "'");
					} else {
						holder.tv_start_time.setText("下半场" + (45 + getNachTime) + "'");
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					holder.tv_start_time.setText("下半场 45'");
					e.printStackTrace();
				}

			} else {
				holder.tv_start_time.setText("下半场 45'");
			}
			holder.tv_time_statu.setTextColor(context.getResources().getColor(R.color.main_red));
			holder.tv_start_time.setVisibility(View.VISIBLE);
			holder.tv_team_result.setText(ballTeamVo.getHscore() + " - " + ballTeamVo.getAscore());
			holder.tv_team_result.setTextColor(context.getResources().getColor(R.color.main_red));
		} else if (ballTeamVo.getState().equals("17")) {
			holder.tv_time_statu.setText("未开赛");
			holder.tv_time_statu.setTextColor(context.getResources().getColor(R.color.black));
			holder.tv_start_time.setVisibility(View.INVISIBLE);
			holder.tv_team_result.setText(LotteryUtils.getStrTimebytimestamp(ballTeamVo.getMtime()));
			holder.tv_team_result.setTextColor(context.getResources().getColor(R.color.black));
		} else {
			holder.tv_time_statu.setText("延期");
			holder.tv_time_statu.setTextColor(context.getResources().getColor(R.color.black));
			holder.tv_start_time.setVisibility(View.INVISIBLE);
			holder.tv_team_result.setText("延期");
			holder.tv_team_result.setTextColor(context.getResources().getColor(R.color.main_bifen_yanqi));
		}
//		holder.lr_Whole.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				// TODO Auto-generated method stub
//				getBalllInfo(ballTeamVo.getXid(),getTeamChangci(ballTeamVo.getXid()));
//			}
//		});
		if (ballTeamVo.getHred().equals("0")) {
			holder.tv_main_hong.setVisibility(View.INVISIBLE);
			holder.lr_main_hong.setVisibility(View.INVISIBLE);
		}else {
			holder.tv_main_hong.setVisibility(View.VISIBLE);
			holder.lr_main_hong.setVisibility(View.VISIBLE);
			holder.tv_main_hong.setText(ballTeamVo.getHred());
		}
		if (ballTeamVo.getAred().equals("0")) {
			holder.tv_gues_hong.setVisibility(View.INVISIBLE);
			holder.lr_gues_hong.setVisibility(View.INVISIBLE);
		}else {
			holder.tv_gues_hong.setVisibility(View.VISIBLE);
			holder.tv_gues_hong.setText(ballTeamVo.getAred());
			holder.lr_gues_hong.setVisibility(View.VISIBLE);
		}
		
		return convertView;
	}

	class childViewHolder {
		ImageView iv_Head;
		TextView tv_team_changci, tv_team_type, tv_start_time, tv_time_statu, tv_team_result;
		TextView tv_peilv_main, tv_peilv_flat, tv_peilv_gues, tv_r_peilv_main, tv_r_peilv_slat, tv_r_peilv_gues;
		TextView tv_main_team_num, tv_main_team_name, tv_main_gues_name, tv_main_gues_num;
		TextView tv_main_hong,tv_gues_hong;
		LinearLayout lr_peilv_show,lr_Whole;
		RelativeLayout lr_main_hong,lr_gues_hong;
		ImageView iv_main_team, iv_gues_team;

	}

	// 二级列表中的item是否能够被选中？可以改为true
	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		return true;
	}

	public String getTeamChangci(String strChangci) {

		String weeknum = "20" + strChangci.substring(0, strChangci.length() - 3);
		String teamNum = strChangci.substring(strChangci.length() - 3, strChangci.length());
		String weekString = "";

		try {
			weekString = LotteryUtils.getTeamWeekOfDate(weeknum);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return weekString + teamNum;
	}
	public void getBalllInfo(String id,final String CaiciId) {
		MySingleton mySingleton = MySingleton.getInstance(context);
		ProgressDialogBar.startProgress(context, "", true);
		StringXmlRequest jsonObjectRequest = new StringXmlRequest(Request.Method.GET,
				"http://01link.igowu123.com/zlk/footballTitleData.go?appversion=462&source=1000&logintype=1&mtype=1&rversion=4.6.2&imei=REQ5MjlGOEJBQzA1M0I4QUFFMjIxOEJFMkJENTMyQ0E%3D&osversion=4.4.2&gameid=0&rid=1442435&gtype=70&roundItemId="
						+ id,
				new Response.Listener<String>() {
					@Override
					public void onResponse(String tn) {

						Log.i("RealTime", "request--------success------" +tn);

						try {
							JSONObject item = XML.toJSONObject(tn);

							

							MainFenxiVo fenxiVo = new MainFenxiVo();
							String resultRep = item.optString("Resp");
							item = new JSONObject(resultRep);
							String result = item.optString("code");

							if (result.equals("0")) {
								fenxiVo.setCode(result);
								fenxiVo.setDesc(item.optString("desc"));

								String getRow = item.optString("row");
								JSONObject itemRow = new JSONObject(getRow);
								
								MainFenxiRowVo rowVo=new MainFenxiRowVo();
								rowVo.setSid(itemRow.optString("sid"));
								rowVo.setItemId(itemRow.optString("itemId"));
								rowVo.setRid(itemRow.optString("rid"));
								rowVo.setHn(itemRow.optString("hn"));
								rowVo.setGn(itemRow.optString("gn"));
								rowVo.setHid(itemRow.optString("hid"));
								rowVo.setGid(itemRow.optString("gid"));
								rowVo.setHomeRank(itemRow.optString("homeRank"));
								
								rowVo.setGuestRank(itemRow.optString("guestRank"));
								rowVo.setTime(itemRow.optString("time"));
								
								rowVo.setHtime(itemRow.optString("htime"));
								rowVo.setHsc(itemRow.optString("hsc"));
								rowVo.setAsc(itemRow.optString("asc"));
								
								rowVo.setType(itemRow.optString("setType"));
								
								
								rowVo.setServerTime(itemRow.optString("serverTime"));
								rowVo.setLeaguename(itemRow.optString("leaguename"));
								
								rowVo.setRoundnum(itemRow.optString("roundnum"));
								rowVo.setLogourl(itemRow.optString("logourl"));
								rowVo.setFollow(itemRow.optString("follow"));
								rowVo.setLive(itemRow.optString("live"));
								rowVo.setHalfsc(itemRow.optString("halfsc"));
								
								fenxiVo.setRow(rowVo);
								
								App.mainFenxiVo=fenxiVo;
								
								Log.e("JSON", App.mainFenxiVo.toString());
								
								Intent intentm = new Intent(context, MainLiveixActivity.class);
                                Bundle bundle=new Bundle();
                                bundle.putString("id", CaiciId);
                                intentm.putExtras(bundle);
								context.startActivity(intentm);

							} else {
								MyToast.getToast(context, item.optString("desc")).show();
							}

						} catch (JSONException e) {
							System.err.println("xml->json失败" + e.getLocalizedMessage());
							MyToast.getToast(context, "获取失败").show();

						}
						ProgressDialogBar.stopProgress();
					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						Log.i("RealTime", "request--------success------" + error);
						MyToast.getToast(context, "获取失败").show();
						ProgressDialogBar.stopProgress();
					}
				}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {

				Map<String, String> params = new HashMap<String, String>();
				// params.put("appid", "0af5281058488ec1784e433f69d45d81");
				// params.put("custNo", "gl00014156");
				// params.put("orderId", attach);

				return params;
			}
		};

		jsonObjectRequest.setShouldCache(false);// 是否设置缓存

		mySingleton.addToRequestQueue(jsonObjectRequest);

	}
}